package com.bwf.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.List;
import java.util.UUID;

/**
 * @Version v1.0
 * @Description: TODO
 * @Author ZHANZHONGXIN
 * @Date 2022/6/14 10:29
 * @Copyright 博为峰
 */
@WebServlet(urlPatterns = "/upload")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Path path = Paths.get("D:\\works22\\upload\\2022-06-14\\53b10c2e权限修饰符.jpg");
        //创建对其文件的字节流
        InputStream inputStream = Files.newInputStream(path);
        //获取写文件的字节流
        ServletOutputStream outputStream = resp.getOutputStream();
        //设置响应头
        resp.setHeader("Content-Type", getServletContext().getMimeType("53b10c2e权限修饰符.jpg"));
        resp.setHeader("Content-Disposition", "attachment;filename" + URLEncoder.encode("53b10c2e权限修饰符.jpg", "utf-8"));
        //响应数据
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(bytes)) > 0) {
            outputStream.write(bytes, 0, len);
        }
        inputStream.close();
        outputStream.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        String name = req.getParameter("name");
        //创建工厂对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置工厂对象的缓存区大小，当上传的文件大小超过缓存值时，就会生成一个临时文件存储到指定的临时目录中
        factory.setSizeThreshold(1024 * 1024 * 10);
        //设置上传时生成的临时文件的保存目录
        Path tempPath = Paths.get("D:\\works22\\temp");
        if (!Files.exists(tempPath)) {
            Files.createDirectory(tempPath);
        }
        //创建文件上传解析器
        ServletFileUpload upload = new ServletFileUpload(factory);
        //监听文件上传进度
        upload.setProgressListener(new ProgressListener() {
            @Override
            public void update(long l, long l1, int i) {
                System.out.println("文件大小是：" + l1 + ",正在处理：" + l);
            }
        });
        //设置文件上传的编码
        upload.setHeaderEncoding("utf-8");
        //设置上传单个文件大小的最大值
        upload.setFileSizeMax(1024 * 1024 * 10);
        //设置上传文件总量的最大值
        upload.setSizeMax(1024 * 1024 * 10);
        //使用文件解析器上传数据
        try {
            List<FileItem> fileItems = upload.parseRequest(req);
            for (FileItem fileItem : fileItems) {
                if (fileItem.isFormField()) {
                    //表单控件名
                    String fieldName = fileItem.getFieldName();
                    //表单控件值
                    String value = fileItem.getString("utf-8");
                    System.out.println("value = " + value);
                } else {
                    //上传文件的名称
                    String uploadFileName = fileItem.getName();
                    //上传文件的类型
                    String uploadFileType = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
                    //上传文件的输入流
                    InputStream inputStream = fileItem.getInputStream();
                    //创建文件保存目录（以当前日期为名称创建目录）
                    LocalDate localDate = LocalDate.now();
                    Path savaPath = Paths.get("D:\\works22\\upload\\" + localDate);
                    if (!Files.exists(savaPath)) {
                        Files.createDirectory(savaPath);
                    }
                    //保存的文件名
                    UUID uuid = UUID.randomUUID();
                    String substring = uuid.toString().substring(0, uuid.toString().indexOf("-"));
                    String saveFileName = substring + uploadFileName;
                    //保存的文件
                    Path saveFile = Paths.get(savaPath + "\\" + saveFileName);
                    //存储文件
                    Files.copy(inputStream, saveFile);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }
}
